import 'dart:convert';

import 'package:dio/dio.dart';

import '../flutter_public.dart';

/// FileName api_interceptor
///
/// @Author lax
/// @Date 2024/3/19
///
/// @Description

class ApiInterceptor extends InterceptorsWrapper {
  /// 请求成功回调
  static Function(Response response)? onRequestSuccess;

  /// 请求异常回调
  static Function(DioError)? onRequestError;

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    onRequestSuccess?.call(response);
    logResponse(response.requestOptions, response);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    logResponse(err.requestOptions, err.response, err);
    if (onRequestError != null) {
      onRequestError?.call(err);
    } else {
      Toast.show(err.response?.data.toString() ?? err.error.toString());
    }
  }

  void logResponse(RequestOptions requestOptions, Response? response,
      [DioError? err]) {
    if (!FlutterPublic.logEnable && !FlutterPublic.printEnable) {
      return;
    }
    final baseUrl = requestOptions.baseUrl;
    final url = requestOptions.path;
    final method = requestOptions.method;
    final headers = requestOptions.headers;
    final para = requestOptions.queryParameters;
    final data = requestOptions.data;
    final resp = response?.data;
    Object? paraJson;
    Object? dataJson;
    Object? respJson;
    try {
      paraJson = jsonEncode(para);
    } catch (_) {
      paraJson = para;
    }
    try {
      dataJson = jsonEncode(data);
    } catch (_) {
      dataJson = data;
    }
    try {
      respJson = jsonEncode(resp);
    } catch (_) {
      respJson = resp;
    }
    final message =
        'url = ${baseUrl + url}\nmethod = $method${headers.isEmpty ? '' : '\nheaders = $headers'}${para.isEmpty ? '' : '\npara = $paraJson'}${data == null ? '' : '\ndata = $dataJson'}\nresp = $respJson${err == null ? '' : '\nerr = ${err.toString()}'}';
    debugLog(message);
  }
}
